package com.gitee.farmer.im.utils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.UUID;

/**
 * @author dong.chengsong
 * @ClassName: HttpUtils
 * @Description: (这里用一句话描述这个类的作用)
 * @date 2022/3/1 10:21
 */
public class HttpUtils {

    public static String uploadFile(String url,String fileType) throws IOException {
        final String uploadFilePath = System.getenv().getOrDefault("file.upload.path", "/tmp/");
        final String yyyyMMdd = LocalDate.now().format(DateTimeFormatter.ofPattern("yyyyMMdd"));
        String fileName = UUID.randomUUID().toString().replace("-","")  + "." + fileType;
        File dir = new File(uploadFilePath + yyyyMMdd);
        if(!dir.exists()){
            dir.mkdirs();
        }
        File localFile = new File(uploadFilePath + yyyyMMdd + "/" + fileName);
        final URL httpUrl = new URL(url);
        final URLConnection urlConnection = httpUrl.openConnection();
        urlConnection.setDoInput(true);
        urlConnection.connect();
        try(final InputStream inputStream = urlConnection.getInputStream(); final FileOutputStream fileOutputStream = new FileOutputStream(localFile)){
            byte[] buf = new byte[1024];
            int len;
            while ((len = inputStream.read(buf))!= -1){
                fileOutputStream.write(buf,0,len);
            }
            fileOutputStream.flush();
        }catch (Exception e){
        }

        return "/" + yyyyMMdd + "/" + fileName;
    }
}
